package com.sinbader.xiaole.common.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.UserKit;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.sinbader.xiaole.common.enums.NumberUtilEnum;
import com.sinbader.xiaole.common.model.xiaolevo.ProductVo;
import com.sinbader.xiaole.common.model.xiaolevo.StockVo;
import com.sinbader.xiaole.common.model.xiaolevo.WarehouseMoveDetailVo;
import com.sinbader.xiaole.common.entity.WarehouseMove;
import com.sinbader.xiaole.common.entity.WarehouseMoveDetail;
import com.sinbader.xiaole.common.mapper.WarehouseMoveDetailMapper;
import com.sinbader.xiaole.common.mapper.WarehouseMoveMapper;
import com.sinbader.xiaole.common.model.params.WarehouseMoveParam;
import com.sinbader.xiaole.common.model.result.WarehouseMoveResult;
import com.sinbader.xiaole.common.service.WarehouseMoveService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinbader.xiaole.common.utils.StringUtil;
import com.sinbader.xiaole.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 仓库移货管理 服务实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WarehouseMoveServiceImpl extends ServiceImpl<WarehouseMoveMapper, WarehouseMove> implements WarehouseMoveService {

    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(WarehouseMoveServiceImpl.class);
    /**
     * warehouseMoveDetailMapper
     */
    @Autowired
    private WarehouseMoveDetailMapper warehouseMoveDetailMapper;

    @Override
    public void add(WarehouseMoveParam param) {
        WarehouseMove entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(WarehouseMoveParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(WarehouseMoveParam param) {
        WarehouseMove oldEntity = getOldEntity(param);
        WarehouseMove newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public WarehouseMoveResult findBySpec(WarehouseMoveParam param) {
        return null;
    }

    @Override
    public List<WarehouseMoveResult> findListBySpec(WarehouseMoveParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(WarehouseMoveParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }


    private Serializable getKey(WarehouseMoveParam param) {
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private WarehouseMove getOldEntity(WarehouseMoveParam param) {
        return this.getById(getKey(param));
    }

    private WarehouseMove getEntity(WarehouseMoveParam param) {
        WarehouseMove entity = new WarehouseMove();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    /**
     * 添加移货信息明细业务处理方法
     *
     * @param detailVo 移货信息
     * @return
     */
    @Override
    public ResponseData addWarehouseMoveInfos(WarehouseMoveDetailVo detailVo) {
        ResponseData responseData = ResponseData.success();
        Map<String, Object> paramMap = new HashMap<>();
        //根据库存id 查询相关产品数据
        paramMap.put("stockId", detailVo.getStockId());

        WarehouseMoveDetailVo baseDataVo = this.baseMapper.getStockInfoById(paramMap);

        //todo 门店id 暂时不做 用户类型的判断（因为：总店就是小乐 小乐和门店没有区别），后续如有变动再做更改
        User user = UserKit.getUser();
        Long shopId = user.getOrgId();
        String userType = user.getType();
        try {
            //移货数量
            Integer moveTotalCount = 0;
            //移货总金额
            BigDecimal moveTotalAmt = BigDecimal.ZERO;

            //获取当前该商品的库存信息
            StockVo stockVo = baseDataVo.getStockVo();
            //商品信息
            ProductVo productVo = baseDataVo.getProductVo();
            //移货数量
            Integer moveCount = 0;
            //移货金额
            BigDecimal moveAmt = BigDecimal.ZERO;
            //取得库存信息的商品 可用库存
            moveCount = stockVo.getWarehouseUsableCount();
            moveAmt = productVo.getUnitPrice() == null ? BigDecimal.ZERO : productVo.getUnitPrice().multiply(new BigDecimal(moveCount));

            //移货项数(种类)
            Integer moveTypeCount = 0;

            //根据当前的 移货单号查询是否已经存在第一条数据
            paramMap.put("moveNum", detailVo.getMoveNum());
            WarehouseMove warehouseMove = baseMapper.selectWarehouMoveByMoveNum(paramMap);
            if (warehouseMove == null) {
                warehouseMove = new WarehouseMove();
                ToolUtil.copyProperties(detailVo, warehouseMove);

                //设置移货日期
                warehouseMove.setMoveDate(new Date());
                warehouseMove.setShopId(shopId);
                moveTotalCount += moveCount;
                moveTotalAmt = moveAmt;
                moveTypeCount++;
                //存在主表单号 只需要在更新该笔数据即可
                warehouseMove.setMoveTotalAmt(moveTotalAmt);
                warehouseMove.setMoveTotalCount(moveTotalCount);
                warehouseMove.setMoveTypeCount(moveTypeCount);
                warehouseMove.setUserType(userType);
                this.baseMapper.insert(warehouseMove);
            } else {
                moveTypeCount++;
                moveTotalCount = warehouseMove.getMoveTotalCount() + moveCount;
                moveTotalAmt = warehouseMove.getMoveTotalAmt().add(moveAmt);
                //存在主表单号 只需要在更新该笔数据即可
                warehouseMove.setMoveTotalAmt(moveTotalAmt);
                warehouseMove.setMoveTotalCount(moveTotalCount);
                warehouseMove.setMoveTypeCount(moveTypeCount);
                this.baseMapper.updateById(warehouseMove);
            }
            //交易明细-商品
            WarehouseMoveDetail detail = new WarehouseMoveDetail();
            ToolUtil.copyProperties(detailVo, detail);
            ToolUtil.copyProperties(productVo, detail);
            detail.setApplyCarModel(productVo.getCarModel());
            detail.setMoveInWarehouseId(detailVo.getMoveInWarehouse());
            detail.setMoveInWarehouseName(detailVo.getMoveInWarehouseName());
            detail.setMoveOutWarehouseId(detailVo.getMoveOutWarehouse());
            detail.setMoveOutWarehouseName(detailVo.getMoveOutWarehouseName());
            detail.setMoveOutShelfId(stockVo.getShelfId());
            detail.setMoveOutShelfName(detailVo.getMoveOutShelfName());
            detail.setMoveInShelfId(detailVo.getMoveInShelfId());
            detail.setMoveInShelfName(detailVo.getMoveInShelfName());
            detail.setMoveCount(moveCount);
            detail.setTotalAmt(moveAmt);
            detail.setProductId(baseDataVo.getProductId());
            detail.setParentId(warehouseMove.getId());
            detail.setDetailNum(StringUtil.getIDNumber(NumberUtilEnum.仓库移货.getName()));
            warehouseMoveDetailMapper.insert(detail);

            //最后更新库存信息中的该商品的仓库id 以及 货架id
            paramMap.put("warehouseId", detailVo.getMoveInWarehouse());
            paramMap.put("shelfId", detailVo.getMoveInShelfId());
            int i = baseMapper.updateStockInfoByStockId(paramMap);
        } catch (Exception e) {
            responseData.setCode(ResponseData.DEFAULT_ERROR_CODE);
            responseData.setMessage("移入失败，请联系管理员！");
            logger.info("插入数据失败：warehouse_move" + e.toString());
            e.printStackTrace();
        } finally {
            return responseData;
        }
    }

    /**
     * 查询当前用户所在门店的 商品库存信息
     *
     * @param productParam 参数
     * @return
     */
    @Override
    public LayuiPageInfo selectProductStockInfos(WarehouseMoveParam productParam) {
        User currentOptUser = UserKit.getUser();
        if (StringUtils.equals("shop", currentOptUser.getType())) {
            productParam.setShopId(UserKit.getOrgId());
        }
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.selectProductStockInfos(pageContext, productParam);
        return LayuiPageFactory.createPageInfo(page);
    }
}
